package com.clm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.clm.constant.MessageConstant;
import com.clm.dto.UserLoginDTO;
import com.clm.entity.User;
import com.clm.exception.LoginFailedException;
import com.clm.mapper.UserMapper;
import com.clm.properties.WeChatProperties;
import com.clm.service.UserService;
import com.clm.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author dinghuapeng
 * @Date 2023/11/5 16:52
 * @PackageName:com.clm.service.impl
 * @ClassName: UserServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {

        String openid = getOpenId(userLoginDTO.getCode());

        //3.判断openid是否为空，为空则表示登陆失败
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //4.判断当前用户是否为新用户
        User user = userMapper.getUserByOpenid(openid);

        //5.如果是新用户，自动完成注册
        if(user==null){
            user=User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //将创建好的用户存入数组
            userMapper.insert(user);
        }

        //6.返回这个用户对象
        return user;
    }

    /**
     * 调用微信接口服务
     * @param code
     * @return
     */
    private String getOpenId(String code){
        //1.调用微信接口服务，获得当前微信用户id，使用哈希表封装
        Map<String,String> map=new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        //2.发送请求
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        //返回的是一个json数组
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }

}
